from flask_appbuilder import ModelView
from flask_appbuilder.fieldwidgets import Select2Widget
from flask_appbuilder.models.sqla.interface import SQLAInterface
from app.models import SerialPortCategory, SerialPort, ResisterRange, Selector, Profile, Tray, VoltageRange, Condition, \
    CheckUnit
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from app import appbuilder, db


def query_profile():
    return db.session.query(Profile)


def query_selector():
    return db.session.query(Selector)


def query_unit():
    return db.session.query(CheckUnit)


def query_voltage():
    return db.session.query(VoltageRange)


class ConditionView(ModelView):
    datamodel = SQLAInterface(Condition)

    list_columns = ['name', 'profile.name', 'selector.name', 'unit.name', 'voltage_a.name', 'voltage_b.name', 'readme']
    edit_form_extra_fields = {'profile': QuerySelectField('Profile',
                                                          query_factory=query_profile,
                                                          widget=Select2Widget()),
                              'selector': QuerySelectField('Selector',
                                                          query_factory=query_selector,
                                                          widget=Select2Widget()),
                              'unit': QuerySelectField('Unit',
                                                          query_factory=query_unit,
                                                          widget=Select2Widget()),
                              'voltage_a': QuerySelectField('VoltageA',
                                                       query_factory=query_voltage,
                                                       widget=Select2Widget()),
                              'voltage_b': QuerySelectField('VoltageB',
                                                       query_factory=query_voltage,
                                                       widget=Select2Widget())}

    show_template = 'Condition/show_cascade.html'
    add_template = 'Condition/add.html'
    edit_template = 'Condition/edit.html'


class VoltageRangeView(ModelView):
    datamodel = SQLAInterface(VoltageRange)
    related_views = [ConditionView]
    list_columns = ['name', 'min', 'max', 'readme']



appbuilder.add_view(ConditionView, "Conditions", icon="fa-folder-open-o", category="Company")
# appbuilder.add_separator("Company")
appbuilder.add_view(VoltageRangeView, "Voltages", icon="fa-folder-open-o", category="Company")

